<?php

namespace Lib\Service;

use Lib\Base\L5;
use Lib\Base\Request;
use Lib\Base\HttpRequest;

class Msdk
{
    /**
     * MSDK解密接口
     * @param array $data = 
     * [
     *      'sig' => 'msdk登录态中的sig参数， 签名信息',
     *      'timestamp' => 'msdk登录态中的timestamp参数， 时间戳',
     *      'appid' => 'msdk登录态中的appid参数， 游戏业务的appid',    
     *      'version' => 'msdk登录态中的version参数, 版本号',
     *      'encode' => 'msdk登录态中的encode参数',
     *      'algorithm' => 'msdk登录态中的algorithm参数',
     *      'msdkEncodeParam' => 'msdk登录态中的msdkEncodeParam参数，加密登录态信息',
     *  ]
     * @return array 用户信息
     */
    public function msdkDecrypt($data)
    {
        $data['sig'] = isset($data['sig']) ? $data['sig'] : Request::param('sig');
        $data['timestamp'] = isset($data['timestamp']) ? $data['timestamp'] : Request::param('timestamp');
        $data['appid'] = isset($data['appid']) ? $data['appid'] : Request::param('appid');
        $data['version'] = isset($data['version']) ? $data['version'] : Request::param('version');
        $data['encode'] = isset($data['encode']) ? $data['encode'] : Request::param('encode');
        $data['algorithm'] = isset($data['algorithm']) ? $data['algorithm'] : Request::param('algorithm');

        recordLog('msdk带解密信息：' . var_export($data, true), __FILE__, __LINE__);

        if (empty($data['sig']) || empty($data['timestamp']) || empty($data['appid']) || empty($data['version']) || empty($data['encode']) || empty($data['algorithm'])) {
            return ['iRet' => -1, 'sMsg' => '需要解密的msdk部分信息缺失！', 'data' => []];
        }

        $msdkEncodeParam = isset($data['msdkEncodeParam']) ? $data['msdkEncodeParam'] : Request::param('msdkEncodeParam');
        unset($data['msdkEncodeParam']);

        $urlInfo = L5::getHostInfo(64082689, 131072);
        if ($urlInfo === false) {
            $urlInfo['url'] = 'http://msdk.qq.com';
        }

        $sUrl = $urlInfo['url'] . "/comm/decrypv1/?sig=" . $data['sig'] . "&timestamp=" . $data['timestamp'] . "&appid=" . $data['appid'] . "&version=" . $data['version'] . "&encode=" . $data['encode'] . "&algorithm=" . $data['algorithm'];

        $msdkEncodeParam = $data['algorithm'] == 'v1' ? urldecode($msdkEncodeParam) : $msdkEncodeParam;

        $http = new HttpRequest(['decode' => false]);

        $retData = $http->post($sUrl, $msdkEncodeParam);
        if ($retData['ret'] != 0) {
            return [
                'iRet' => $retData['ret'],
                'sMsg' => $retData['msg'],
                'data' => $retData['data']
            ];
        } else {
            $result = [];
            parse_str($retData['data'], $result);
            return ['iRet' => 0, 'sMsg' => 'success', 'data' => $result];
        }
    }

    /**
     * MSDK方式获取QQ或者微信用户基本信息
     * @param array $data =
     * [
     *      'acctype' => 'msdk登录态中的acctype参数',
     *      'sig' => 'msdk登录态中的sig参数， 加密串。如果没有该参数，就必须传递参数appkey',
     *      'appkey' => '该参数为相关应用在MSDK中注册的appkey而不是在微信或者QQ公共平台中注册生成的appkey（如果传了sig参数，就不需要传）',
     *      'timestamp' => '时间戳， 生成sig使用，传了appkey就不需要该参数',
     *      'access_token' => 'msdk登录态中的access_token参数',
     *      'appid' => 'msdk登录态中的appid参数',
     *      'openid' => 'msdk登录态中的openid参数',
     *      'encode' => 'msdk登录态中的encode参数'
     * ]
     * @return array 用户信息数组
     */
    public function getMSDKUserInfo($data)
    {
        $retData = array();

        //参数检查
        if (!isset($data['acctype']) || ($data['acctype'] != 'qq' && $data['acctype'] != 'weixin')) {
            $retData['iRet'] = '-1';
            $retData['sMsg'] = '缺少参数acctype，或者参数值不正确（qq|wx）';
            return $retData;
        }

        if (!isset($data['sig']) || $data['sig'] == '') {
            //如果没有传递签名信息，就必须传递应用在MSDK中的appkey(不是应用在微信开放平台或者QQ开放平台的appkey)来计算
            if (!isset($data['appkey']) || $data['appkey'] == '') {
                $retData['iRet'] = '-2';
                $retData['sMsg'] = '缺少参数appkey';
                return $retData;
            }
            $data['timestamp'] = time();
            $data['sig'] = md5($data['appkey'] . $data['timestamp']);
        } else {
            if (!isset($data['timestamp']) || $data['timestamp'] == '') {
                $retData['iRet'] = '-3';
                $retData['sMsg'] = '缺少参数timestamp';
                return $retData;
            }
        }

        if (!isset($data['access_token']) || $data['access_token'] == '') {
            $retData['iRet'] = '-4';
            $retData['sMsg'] = '缺少参数access_token';
            return $retData;
        }

        if (!isset($data['openid']) || $data['openid'] == '') {
            $retData['iRet'] = '-5';
            $retData['sMsg'] = '缺少参数openid';
            return $retData;
        }

        $sInterface = '';
        $postData = array();

        if ($data['acctype'] == 'qq') {
            if (!isset($data['appid']) || $data['appid'] == '') {
                $retData['iRet'] = '-6';
                $retData['sMsg'] = '缺少参数appid';
                return $retData;
            }

            $sInterface = 'qqprofile';

            $postData['appid'] = $data['appid']; /*此参数如果获取微信用户基本信息，不需要传*/
            $postData['accessToken'] = $data['access_token'];
            $postData['openid'] = $data['openid'];
        } else {
            $sInterface = 'wxprofile';

            $postData['accessToken'] = $data['access_token'];
            $postData['openids'] = array($data['openid']);
        }

        if (!isset($data['encode'])) {
            $data['encode'] = '1';
        }

        $urlInfo = L5::getHostInfo(64082689, 131072);
        if ($urlInfo === false) {
            $urlInfo['url'] = 'http://msdk.qq.com';
        }

        $sUrl = $urlInfo['url'] . "/relation/" . $sInterface . "/?timestamp=" . $data['timestamp'] . "&appid=" . $data['appid'] . "&sig=" . $data['sig'] . "&openid=" . $data['openid'] . "&encode=" . $data['encode'];

        $http = new HttpRequest(['decode' => true]);
        $data = $http->post($sUrl, json_encode($postData));
        return [
            'iRet' => $data['ret'],
            'sMsg' => $data['msg'],
            'data' => $data['data']
        ];
    }
}
